package svc

import (
	"github.com/apache/rocketmq-client-go/v2"
	"github.com/go-redis/redis/v8"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
	distributed "go-zero-demo/distributed-id-rpc/distributed"
	"go-zero-demo/user-api/internal/config"
	"go-zero-demo/user-api/internal/initialize/mq"
	"go-zero-demo/user-api/internal/initialize/mq/transaction"
	initialize "go-zero-demo/user-api/internal/initialize/redis"
	"go-zero-demo/user-api/internal/middleware"
	"go-zero-demo/user-rpc/usercenter"
)

type ServiceContext struct {
	Config              config.Config
	TestMiddleware      rest.Middleware
	UserCenterClient    usercenter.UserCenter
	DistributedIdClient distributed.Distributed
	RedisClient         *redis.Client
	UniversalProducer   rocketmq.Producer
	TransactionProducer rocketmq.TransactionProducer
}

func NewServiceContext(c config.Config) *ServiceContext {
	// init user rpc interface ...
	userClientConf := zrpc.RpcClientConf{}
	// # nacos://[user:passwd]@host/service?param=value'
	userClientConf.Target = c.UserRpc.Target
	userClientConf.NonBlock = true
	userClientConf.Timeout = 3000
	userClient := zrpc.MustNewClient(userClientConf)
	// init distributed rpc interface ...
	distributedClientConf := zrpc.RpcClientConf{}
	// # nacos://[user:passwd]@host/service?param=value'
	distributedClientConf.Target = c.DistributedIdRpc.Target
	distributedClientConf.NonBlock = true
	distributedClientConf.Timeout = 3000
	distributedClient := zrpc.MustNewClient(distributedClientConf)
	// init redis
	initRedis, redisErr := initialize.InitRedis(c.Redis)
	serviceContext := &ServiceContext{
		Config: c,
		// 注册
		TestMiddleware:      middleware.NewTestMiddleware().Handle,
		UserCenterClient:    usercenter.NewUserCenter(userClient),
		DistributedIdClient: distributed.NewDistributed(distributedClient),
	}
	if redisErr != nil {
		logx.Error(redisErr)
		return serviceContext
	}
	serviceContext.RedisClient = initRedis
	// init mq producer
	producer, mqErr := mq.InitUniversalProducer()
	if mqErr != nil {
		logx.Error(mqErr)
		return serviceContext
	}
	serviceContext.UniversalProducer = producer

	// init transaction producer
	transactionProducer, transactionProducerErr := transaction.InitTransactionProducer()
	if transactionProducerErr != nil {
		logx.Error(transactionProducerErr)
		return serviceContext
	}
	serviceContext.TransactionProducer = transactionProducer

	// init mq consume
	mq.InitUniversalConsumer("user-api-register-topic")
	return serviceContext

}
